package com.smt.common.aspect;

import com.smt.modules.app.annotation.FileSize;
import com.smt.modules.app.utils.FileSizeUtil;
import com.smt.modules.bus.entity.MemberUserEntity;
import com.smt.modules.bus.service.MemberUserService;
import com.smt.modules.bus.vo.DocumentVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Arrays;

/**
 * 增强文件上传或下载 TODO
 *
 * @author zhangyi
 * @date 2018/10/10 14:47
 */
@Aspect
@Component
@Slf4j
@ConfigurationProperties(prefix = "user.file")
public class FileSizeAspect {

    @Autowired
    private MemberUserService memberUserService;
    private Long maxSize;
    public Long getMaxSize() {
        return maxSize;
    }
    public void setMaxSize(Long maxSize) {
        this.maxSize = maxSize;
    }

    /**
     * 用户操作文件动作：上传
     */
    public static final String FILE_UPLOAD = "upload";
    /**
     * 用户操作文件动作：删除
     */
    public static final String FILE_DELETE = "delete";
    /**
     * 用户操作文件动作：更新
     */
    public static final String FILE_UPDATE = "update";

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.smt.modules.app.annotation.FileSize)")
    public void fileOperate() {}
    /**
     * 根据行为编写 TODO
     *
     * @param joinPoint
     */
    @After("fileOperate()")
    public void fileOperateAfter(JoinPoint joinPoint) {

        //判断此用户是上传文件还是删除文件还是更新
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        MemberUserEntity[] m  = new MemberUserEntity[]{null};
        long[] userId = new long[]{0};
        StringBuffer fileUrl = new StringBuffer();
        //操作状态
        boolean operateStatus = false;
        FileSize fileOperate = method.getAnnotation(FileSize.class);
        String operate = fileOperate.operate();
        Object[] args = joinPoint.getArgs();
        Arrays.asList(args).stream()
                .forEach(e -> {
                    if (e instanceof DocumentVo) {
                        DocumentVo d = (DocumentVo) e;
                        fileUrl.append(d.getFileUrl());
                    } else if (e instanceof MemberUserEntity) {
                         m[0] = (MemberUserEntity) e;
                        userId[0] = m[0].getUserId();
                    }
                });
        if(!"null".equals(fileUrl)) {
            double fileSizeToNumber = FileSizeUtil.getFileSizeToNumber(fileUrl.toString());
            if (userId[0] != 0 && fileUrl != null) {
                if (FILE_UPLOAD.equals(operate)) {
                    operateStatus = updateAdd(userId, m, fileSizeToNumber);
                    //存入数据库记录

                } else if (FILE_DELETE.equals(operate)) {
                    operateStatus = updateSubtract(userId, m, fileSizeToNumber);
                } else if (FILE_UPDATE.equals(operate)) {
                    if (fileSizeToNumber < m[0].getSumSize()) {
                        operateStatus = updateSubtract(userId, m, fileSizeToNumber);
                    } else {
                        operateStatus = updateAdd(userId, m, fileSizeToNumber);
                    }
                }
            }
        }
        if(!operateStatus){
            //失败   待定

        }else{
            //成功

        }
    }

    /**
     * 文件增加更新
     *
     * @param userId
     * @param m
     * @param fileSizeToNumber
     * @return
     */
    private boolean updateAdd(long[] userId,MemberUserEntity[] m,double fileSizeToNumber){
        boolean flag = false;
        //用户存储文件的总大小
        Double sumSize = new BigDecimal(m[0].getSumSize()).add(new BigDecimal(fileSizeToNumber)).doubleValue();
        //判断是否上超过上线水平
        if(sumSize>maxSize){
            //超过上限值
            log.error("您网盘容量不足");
        }else{
            flag = memberUserService.updateSumFileSize(userId[0],sumSize);
        }
        return flag;
    }

    /**
     * 文件减少更新
     *
     * @param userId
     * @param m
     * @param fileSizeToNumber
     * @return
     */
    private boolean updateSubtract(long[] userId,MemberUserEntity[] m,double fileSizeToNumber){
        Double sumSize = new BigDecimal(m[0].getSumSize()).subtract(new BigDecimal(fileSizeToNumber)).doubleValue();
        return memberUserService.updateSumFileSize(userId[0],sumSize);
    }
}
